package com.manshutingyu.auth.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.manshutingyu.common.core.properties.MySecurityProperties;
import com.manshutingyu.common.core.constants.SecurityConstants;
import com.manshutingyu.common.core.dto.*;
import com.manshutingyu.common.core.exception.BusinessException;
import com.manshutingyu.common.core.utils.JwtUtils;
import com.manshutingyu.system.api.feign.RemoteSysUserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author：yinyuxia
 * @Date：2025/4/28 10:23
 */
@Service
public class LoginService {
    @Resource
    private MySecurityProperties mySecurityProperties;
    @Resource
    private RemoteSysUserService remoteSysUserService;

    public LoginResultDTO login(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException("用户/密码必须填写");
        }
        LoginResultDTO res = new LoginResultDTO();
        String accessToken;
         Long expiration = mySecurityProperties.getJwt().getTtl();
        // 查询用户信息
        R<LoginUserDTO> userResult = remoteSysUserService.loadUserByUsername(username);
        if (userResult == null || userResult.getCode().equals(500)) {
            throw new BusinessException(userResult.getMsg());
        }
        LoginUserDTO userInfo = userResult.getData();
        if (userInfo.getDelFlag() == 1) {
            throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
        }
        if (userInfo.getDelFlag() == 1) {
            throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
        }
        if (userInfo.getStatus().equals("0")) {
            throw new BusinessException("对不起，您的账号：" + username + " 已停用");
        }
        /*if (!userInfo.getPassword().equals(new BCryptPasswordEncoder().encode(password))) {
            throw new BusinessException("对不起，您的账号：" + username + " 密码错误");
        }*/
        // 认证成功后生成JWT令牌
        accessToken = JwtUtils.createToken(userInfo);
        res.setToken(accessToken);
        res.setExpiration(expiration);
        res.setTokenType(StrUtil.trim(SecurityConstants.JWT_TOKEN_PREFIX));
        return res;
    }

    public UserInfoResultDTO getInfo(String username) {
        R<LoginUserDTO> userResult = remoteSysUserService.loadUserByUsername(username);
        if (userResult == null || userResult.getCode().equals(500)) {
            throw new BusinessException(userResult.getMsg());
        }
        LoginUserDTO userInfo = userResult.getData();
        UserInfoResultDTO result = new UserInfoResultDTO();
        result.setUsername(userInfo.getUserName());
        result.setPermissions(userInfo.getPermissions());
        result.setRoles(userInfo.getRoles());
        result.setUserInfo(BeanUtil.copyProperties(userInfo, SysUserInfoDTO.class));
        return result;
    }
}
